<template>
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="850px" append-to-body>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="auto"
      :disabled="disabled"
      :class="{ 'detail-disabled': disabled }"
    >
      <el-row>
        <el-col :span="18">
          <el-form-item label="合同分类" prop="contractCategory">
            <el-select v-model="form.contractCategory" placeholder="请选择合同分类" clearable>
              <el-option
                v-for="dict in dict.type.contract_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value * 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="合同进度" prop="contractProgress">
            <el-select v-model="form.contractProgress" placeholder="请选择合同进度" clearable>
              <el-option
                v-for="dict in dict.type.contract_progress"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value * 1"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="封面" prop="coverImg">
            <image-upload
              :limit="1"
              @input="
                (val) => {
                  form.coverImg = val
                }
              "
              :value="form.coverImg"
            />
          </el-form-item> -->
          <el-form-item label="合同名称" prop="contractName">
            <el-input v-model="form.contractName" placeholder="请输入合同名称" />
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNumber">
            <el-input v-model="form.contractNumber" placeholder="请输入合同编号" />
          </el-form-item>

          <el-form-item label="合同负责人" prop="contractManager">
            <el-input v-model="form.contractManager" placeholder="请输入合同负责人" />
          </el-form-item>
          <el-form-item
            label="供应商"
            prop="supplierId"
            v-if="form.contractCategory != '1'"
            :rules="[
              {
                required: true,
                message: '请选择供应商',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <el-select
              v-model="form.supplierId"
              filterable
              remote
              reserve-keyword
              placeholder="输入关键词，可获取更多供应商"
              :remote-method="getSupplierList"
              :loading="supplierLoading"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in supplierList"
                :key="`key_${item.id}`"
                :label="item.supplierName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="客户"
            prop="customerId"
            v-if="form.contractCategory == '1'"
            :rules="[
              {
                required: form.contractCategory == '1',
                message: '请选择客户',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <el-select
              v-model="form.customerId"
              placeholder="输入关键词，可获取更多客户"
              :remote-method="getCustomer"
              filterable
              remote
              reserve-keyword
              clearable
              v-loading="customeLading"
              @clear="customerClear"
            >
              <el-option
                v-for="item in customeList"
                :key="`key_${item.id}`"
                :label="item.customerName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="项目"
            prop="projectId"
            :rules="[
              {
                required: form.contractCategory == '3' || form.contractCategory == '1',
                message: '输入关键词，可获取更多项目',
                trigger: ['change', 'blur'],
              },
            ]"
          >
            <el-select
              v-model="form.projectId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="getProjectList"
              :loading="projectLoading"
              clearable
              style="width: 100%"
            >
              <el-option v-for="item in projectList" :key="`key_${item.id}`" :label="item.projectName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="合同金额" prop="contractAmount">
            <el-input-number
              controls-position="right"
              :step="100"
              :min="0"
              style="width: 150px"
              :precision="2"
              v-model="form.contractAmount"
              placeholder="请输入合同金额"
            >
            </el-input-number>
            元
          </el-form-item>
          <el-form-item label="合同负责主体" prop="contractResponsibleParty">
            <el-input v-model="form.contractResponsibleParty" placeholder="请输入合同负责主体" />
          </el-form-item>
          <el-form-item label="中标时间" prop="winBiddingDate">
            <el-date-picker
              clearable
              v-model="form.winBiddingDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择中标时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="合同签订时间" prop="contractSignDate">
            <el-date-picker
              clearable
              v-model="form.contractSignDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择合同签订时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="签约主体" prop="signObject">
            <el-input v-model="form.signObject" placeholder="请输入签约主体" />
          </el-form-item>
          <el-form-item label="附件列表" prop="annexDtoList">
            <file-upload
              valueType="object"
              :fileType="['pdf', 'doc', 'docx', 'xls', 'xlsx']"
              :fileSize="10"
              :limit="20"
              :value="form.annexDtoList"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider></el-divider>
    <div class="title" style="padding-top: 0px">
      合同明细<el-button @click="handleOpenModel('moreInfo')" :disabled="disabled" type="warning" size="mini"
        >新增</el-button
      >
    </div>
    <el-table :data="form.contractInformationDetailList" style="width: 99%; margin: 0 auto">
      <el-table-column label="序号" type="index" align="center" :index="indexMethod"> </el-table-column>
      <el-table-column algin align="center" label="费用类型名称">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.contract_expense" :value="scope.row.expenseType" />
        </template>
      </el-table-column>
      <el-table-column prop="num" align="center" label="数量"> </el-table-column>
      <el-table-column prop="amount" align="center" label="金额"> </el-table-column>
      <el-table-column align="center" label="操作" width="160px">
        <template slot-scope="scope">
          <el-button
            :disabled="disabled"
            type="text"
            size="mini"
            @click="handleOpenModel('moreInfo', scope.row, scope.$index)"
            >编辑</el-button
          >
          <el-button
            :disabled="disabled"
            type="text"
            size="mini"
            @click="handleDelete('contractInformationDetailList', scope.$index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="title" style="margin-top: 10px">
      回款节点和付款节点<el-button @click="handleOpenModel('plan')" :disabled="disabled" type="warning" size="mini"
        >新增</el-button
      >
    </div>
    <el-table :data="form.contractPaymentPlanList" style="width: 99%; margin: 0 auto">
      <el-table-column prop="stageName" align="center" label="阶段名称"> </el-table-column>
      <el-table-column prop="paymentCondition" align="center" label="付款条件"> </el-table-column>
      <el-table-column prop="paymentAmount" align="center" label="金额"> </el-table-column>
      <el-table-column prop="paymentPercentage" align="center" label="支付比例">
        <template slot-scope="scope"> {{ scope.row.paymentPercentage || '0' }}% </template>
      </el-table-column>
      <el-table-column prop="plannedPaymentDate" align="center" label="计划支付时间"> </el-table-column>
      <el-table-column align="center" label="支付状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.plan_status" :value="scope.row.paymentStatus" />
        </template>
      </el-table-column>
      <el-table-column prop="actualPaymentDate" align="center" label="实际支付时间"> </el-table-column>
      <el-table-column align="center" label="操作"
        ><template slot-scope="scope">
          <el-button :disabled="disabled" @click="handleOpenModel('plan', scope.row, scope.$index)" type="text"
            >编辑</el-button
          >
          <el-button
            :disabled="disabled"
            type="text"
            style="margin-left: 0"
            @click="handleDelete('contractPaymentPlanList', scope.$index)"
            >删除</el-button
          >
        </template></el-table-column
      >
    </el-table>
    <div style="margin-top: 8px">
      付款金额合计：<span style="color: red; margin-right: 2px; font-size: 18px">{{
        totalPayment(form.contractPaymentPlanList)
      }}</span
      >元
    </div>
    <div class="title" style="margin-top: 10px">
      合同推荐计划<el-button @click="handleOpenModel('recommend')" :disabled="disabled" type="warning" size="mini"
        >新增</el-button
      >
    </div>
    <el-table :data="form.contractAdvancePlanList" style="width: 99%; margin: 0 auto">
      <el-table-column prop="title" align="center" label="计划名称"> </el-table-column>
      <el-table-column prop="content" align="center" label="计划内容"> </el-table-column>
      <el-table-column prop="manager" align="center" label="负责人"> </el-table-column>
      <el-table-column prop="startTime" align="center" label="计划开始时间"> </el-table-column>
      <el-table-column prop="endTime" align="center" label="计划结束时间"> </el-table-column>
      <el-table-column align="center" label="操作" widht="120px"
        ><template slot-scope="scope">
          <el-button :disabled="disabled" @click="handleOpenModel('recommend', scope.row, scope.$index)" type="text"
            >编辑</el-button
          >
          <el-button
            style="margin-left: 0px"
            :disabled="disabled"
            type="text"
            @click="handleDelete('contractAdvancePlanList', scope.$index)"
            >删除</el-button
          >
        </template></el-table-column
      >
    </el-table>
  </el-dialog>
</template>
<script>
import { getInformation } from '@/api/biz/contract'
import { listProject } from '@/api/biz/project'
import { listSupplier } from '@/api/biz/supplier'
import { listCustomer } from '@/api/biz/customer'

export default {
  name: 'ContractDetailsChildren',
  components: {},
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String || Number,
      default: '',
    },
  },
  data() {
    return {
      disabled: true,
      open: false,
      title: '',
      // 遮罩层
      loading: true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractCategory: [{ required: true, message: '请选择合同类型', trigger: 'change' }],
        contractProgress: [{ required: true, message: '请选择合同进度', trigger: 'change' }],
        contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
        contractNumber: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
        contractManager: [{ required: true, message: '请填写合同负责人', trigger: 'blur' }],
        signObject: [{ required: true, message: '请填写签约主体', trigger: 'blur' }],
        createTime: [{ required: true, message: '创建时间不能为空', trigger: 'blur' }],
        updateTime: [{ required: true, message: '更新时间不能为空', trigger: 'blur' }],
        contractResponsibleParty: [{ required: true, message: '请填写合同负责主体', trigger: 'blur' }],
      },
      dataSource: {},
      supplierList: [],
      supplierLoading: false,
      projectList: [],
      projectLoading: false,
      currentIndex: -1,
      modelName: '',
      modelData: {},
      customeData: {},
      customeList: [],
      customeLading: false,
    }
  },
  dicts: ['contract_category', 'contract_progress', 'contract_expense', 'plan_status'],
  watch: {
    show: {
      handler(val) {
        this.open = val
      },
    },
    open: {
      handler(val) {
        this.reset()
        if (val) {
          if (this.disabled) {
            this.title = '查看合同信息'
          } else {
            this.title = this.id ? '修改合同信息' : '添加合同信息'
          }
          if (this.id) {
            getInformation(this.id).then((response) => {
              this.projectList = [
                ...this.projectList,
                {
                  projectName: response.data.projectName,
                  id: response.data.projectId,
                },
              ]
              this.customeList = [
                ...this.customeList,
                {
                  customerName: response.data.customerName,
                  id: response.data.customerId,
                },
              ]
              this.supplierList = [
                ...this.supplierList,
                {
                  supplierName: response.data.supplierName,
                  id: response.data.supplierId,
                },
              ]
              this.form = response.data
            })
          } else {
            this.getSupplierList()
            this.getProjectList()
            this.getCustomer()
          }
        } else {
          this.supplierList = []
          this.projectList = []
          this.$emit('cancel', false)
        }
      },
    },
  },
  methods: {
    totalPayment(data = []) {
      const arr = data.map((item) => item.paymentAmount)
      return arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0)
    },
    customerClear() {
      this.form.customerId = null
      this.form.customerName = null
    },
    getCustomer(query = '') {
      this.customeLading = true
      listCustomer({ customerName: query, pageNum: 1, pageSize: 10 })
        .then((res) => {
          this.customeList = res.rows
          this.customeLading = false
        })
        .catch((error) => {
          this.customeLading = false
        })
    },
    // 取消按钮
    cancel() {
      this.reset()
      this.open = false
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        contractCategory: null,
        contractProgress: null,
        contractName: null,
        contractNumber: null,
        contractManager: null,
        supplierId: null,
        projectId: null,
        contractAmount: null,
        contractResponsibleParty: null,
        winBiddingDate: null,
        contractSignDate: null,
        signObject: null,
        customerId: null,
        customerName: null,
        contractInformationDetailList: [],
        contractPaymentPlanList: [],
        contractAdvancePlanList: [],
        coverImg: null,
        annexDtoList:null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleOpenModel(name = '', data = {}, index = -1) {
      this.modelName = name
      this.modelData = data
      this.currentIndex = index
    },
    getSupplierList(query = '') {
      this.supplierLoading = false
      listSupplier({
        supplierName: query,
        pageNum: 1,
        pageSize: 10,
      })
        .then((res) => {
          const result = res.rows
          this.supplierList = result

          this.supplierLoading = false
        })
        .catch((err) => {
          this.supplierLoading = false
          this.supplierList = []
        })
    },
    getProjectList(query = '') {
      this.projectLoading = true
      listProject({
        projectName: query,
        pageNum: 1,
        pageSize: 10,
      })
        .then((res) => {
          const result = res.rows
          this.projectList = result
          this.projectLoading = false
        })
        .catch((err) => {
          this.projectLoading = false
          this.projectList = []
        })
    },
    saveModelData({ name, data }) {
      const list = [...this.form[name]]
      if (this.currentIndex > -1) {
        list[this.currentIndex] = data
      } else {
        list.push(data)
      }
      this.form[name] = list
      this.handleOpenModel()
    },
    indexMethod(index) {
      return (index + 1) * 1
    },
    handleDelete(agsName, index) {
      const list = this.form[agsName]
      list.splice(index, 1)
      this.form[agsName] = list
    },
  },
}
</script>
<style scoped lang="scss">
.scrollMenuBox {
  width: 100%;
  height: 450px;
}
.title {
  padding: 15px 0;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
